package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"server/global"
	"server/model"
)

func init() {
	Viper()
	Nacos()
	Mysql()
}

func Viper() {
	viper.SetConfigFile("./dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.NacosConfig)
	fmt.Println("nacos", global.NacosConfig)
}
func Nacos() {
	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.Nacos.NameSpace,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
		Username:            global.NacosConfig.Nacos.Username,
		Password:            global.NacosConfig.Nacos.Password,
	}
	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.NacosConfig.Nacos.Addr,
			ContextPath: "/nacos",
			Port:        global.NacosConfig.Nacos.Port,
			Scheme:      "http",
		},
	}
	// Another way of create config client for dynamic configuration (recommend)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.Nacos.DataId,
		Group:  global.NacosConfig.Nacos.Group})
	//fmt.Println(content)
	json.Unmarshal([]byte(content), &global.Config)
	fmt.Println(global.Config)
}

func Mysql() {
	var err error
	config := global.Config.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.User, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql")
	//global.DB.AutoMigrate(&model.Video{})
	global.DB.AutoMigrate(&model.VideoUser{})
}
